#pragma once
#include <iostream>
#include <string>
#include <sys/epoll.h>
#include "Log.hpp"
#include "Err.hpp"

const static int defaultepfd = -1;
const static int gsize = 128;

// epll模型
class Epoller
{
public:
    Epoller() : epfd_(defaultepfd)
    {
    }
    void Create()
    {
        epfd_ = epoll_create(gsize);
        if (epfd_ < 0)
        {
            logMessage(Fatal, "epoll create error,code: %d, errstring: %s", errno, strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }
    //添加事件(用户-》内核) epoll_ctl
    bool AddModEvent(int fd,uint32_t events,int op)
    {
        struct epoll_event ev;
        ev.events=events;
        ev.data.fd=fd;
        int n=epoll_ctl(epfd_,op,fd,&ev);
        if(n<0)
        {
             logMessage(Fatal, "epoll_ctl error,code: %d, errstring: %s", errno, strerror(errno));
            return false;
        }
        return true;
    }
    bool DelEvent(int fd)
    {
        // epoll在操作fd的时候，有一个要求，fd必须合法！
        return epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, nullptr) == 0;
    }
    // bool ModEvent(int fd,uint32_t events)
    // {
    //     struct epoll_event ev;
    //     ev.events=events;
    //     ev.data.fd=fd;
    //     int n=epoll_ctl(epfd_,EPOLL_CTL_MOD,fd,&ev);
    // }
    int Wait(struct epoll_event* revs,int num,int timeout)
    {
        return epoll_wait(epfd_,revs,num,timeout);
    }

    int Fd()
    {
        return epfd_;
    }
    void Close()
    {
        if (epfd_ != defaultepfd)
            close(epfd_); // epoll_create用完之后必须调用close关闭
    }
    ~Epoller()
    {
    }

private:
    int epfd_;
};
